import re

from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from users.models import User
from django_redis import get_redis_connection


class UserSerializers(serializers.ModelSerializer):
    # 显示指明模型类中没有的字段
    password2 = serializers.CharField(max_length=20, min_length=8, write_only=True)
    allow = serializers.CharField(write_only=True)
    sms_code = serializers.CharField(max_length=6, min_length=6, write_only=True)
    token = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ('username', 'password', 'password2', 'mobile', 'allow', 'sms_code', 'id', 'token')
        extra_kwargs = {
            'password': {'max_length': 20, 'min_length': 8, 'write_only': True},
            'username': {'max_length': 20, 'min_length': 5},
        }

    # 验证手机号格式
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机格式不匹配')
        return value

    # 验证选中状态
    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('协议未同意')
        return value

    # 验证两次密码和短信验证
    def validate(self, attrs):
        # 判断用户名是否是手机格式
        if re.match(r'^1[3-9]\d{9}$', attrs['username']):
            if attrs['username'] != attrs['mobile']:
                raise serializers.ValidationError('用户名和手机号不一致')
        # 两次密码判断
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('两次密码不一致')
        # 判断短信验证码
        # 1、获取缓存真实的短信验证码
        conn = get_redis_connection('sms_code')
        real_sms_code = conn.get('sms_code_%s' % attrs['mobile'])
        # 2、判断短信验证码是否失效
        if real_sms_code is None:
            raise serializers.ValidationError('短信验证码已失效')
        # 3、将用户传递填写的短信验证码与真实的短信验证码比较
        if attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('输入的短信验证码有误')
        return attrs

    # 保存
    def create(self, validated_data):
        # # 方式一
        # del validated_data['password']
        # del validated_data['sms_code']
        # del validated_data['allow']
        ## user = User.objects.create() #不会对密码进行加密
        # user = User.objects.create_user(**validated_data)
        # jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        #
        # payload = jwt_payload_handler(user)
        # token = jwt_encode_handler(payload)
        # user.token = token
        # return user

        # 方式二
        user = User.objects.create_user(username=validated_data['username'], password=validated_data['password'],
                                        mobile=validated_data['mobile'])

        # 生成jwt token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        # 给user对象添加token属性
        user.token = token
        return user


class UserShowSerializers(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'mobile', 'email', 'id')


class UpdatePasswordSerializer(serializers.ModelSerializer):
    new_password = serializers.CharField(max_length=20, min_length=8, write_only=True)
    password2 = serializers.CharField(max_length=20,min_length=8, write_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'password2', 'new_password']
        extra_kwargs = {
            'password': {'max_length': 20, 'min_length': 8, 'write_only': True},
            'username': {'max_length': 20, 'min_length': 5},
        }

        # 验证两次新密码是否一致
        def validate(self, attrs):
            # 两次密码判断
            if attrs['password'] != attrs['password2']:
                raise serializers.ValidationError('两次密码不一致')

        # 请求方式 ： PUT
        # 请求参数： 表单
        # 请求路径： / users / user_id / password /
        # 参数         类型  是否必须   说明
        # user_id       int   是     用户id
        # username      str   是     用户名
        # old_password  str   是     当前密码
        # password      str   是   新密码
        # Password2     str   是   确认新密码

        # 返回数据： JSON
        # 参数      类型      是否必须        说明
        # user_id     str     是       用户id
        # username    str     是       用户名

        ##用户中心重置密码
        # 业务逻辑：
        # 1、继承自UpdateAPIView
        # 2、指定序列化器，重写get_object()方法，查找指定用户
        # 3、使用序列化器
        # 4、验证老密码和输入的老密码是否一致
        # 5、验证两次新密码是否一样
        # 6、注意密码保存使用密文
        # 7、更新密码
        # 8、返回结果，前端刷新

        # def pass_info():
        #
        #     # 1. 获取到传入参数
        #     data_dict = request.json
        #     old_password = data_dict.get("old_password")
        #     new_password = data_dict.get("new_password")
        #
        #     if not all([old_password, new_password]):
        #         return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
        #
        #     # 2. 获取当前登录用户的信息
        #     user = g.user
        #
        #     if not user.check_passowrd(old_password):
        #         return jsonify(errno=RET.PWDERR, errmsg="原密码错误")
        #
        #     # 更新数据
        #     user.password = new_password
        #     try:
        #         db.session.commit()
        #     except Exception as e:
        #         current_app.logger.error(e)
        #         db.session.rollback()
        #         return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
        #
        #     return jsonify(errno=RET.OK, errmsg="保存成功")
